﻿/* ----------------------------------------
* Чат
* options = {
                chat:               SignalR прокси-объект чата
*				roomKey: 			Ключ комнаты
*				senderName: 		имя пользователя
*			}
*/
$.fn.chat = function (options) {

    var chatCode = '<div class="chat_content"></div>' +
        '<div class="chat_form"><form action="#">' +
        '<button id="sendMessage" class="btn_light" type="button"><span class="icon icon_enter"></span></button>' +
        '<textarea id="msg" placeholder="Сообщение"></textarea></form></div>';
    $(this).append(chatCode);

    var chatContent = $(this).find(".chat_content"),
        messageInput = $(this).find("#msg");


    chat.OnSend = function (msg) {
        var msgClass = 'chat_message';
        if (msg.SenderName == options.senderName)
            msgClass += ' chat_mes_my';
        chatContent.append(
            '<div class="' + msgClass + '"><div class="chat_mes_title"><span class="name">' +
                msg.SenderName +
                '</span><span class="date">' + msg.FormattedDate + '</span></div><div class="chat_mes_text">' +
                msg.Content +
                '</div></div>');

        chatContent.scrollTop(chatContent[0].scrollHeight - chatContent.height());
    };

    $(this).find("#sendMessage").click(sendMessage);

    $(this).find('#msg').keydown(function (e) {
        if (e.keyCode == 13 && !e.shiftKey) {
            sendMessage();
            return false;
        }
        return true;
    });

    function sendMessage() {
        var msg = {
            'Address': options.address,
            'ConnectionId': options.connectionId,
            'Name': options.accountName,
            'Message': messageInput.val()
        };
        chat.send(msg);
        messageInput.val("");
        messageInput.focus();
    }
};

$.fn.fixHeight = function (callback) {
    var fixItem = $(this);

    $(window).bind('load', fix);
    $(window).bind('resize', fix);

    function fix() {
        var height = callback();
        fixItem.css('height', height);
    }
};